package com.lzxzjy.web.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lzxzjy.pojo.Book;
import com.lzxzjy.pojo.Reader;
import com.lzxzjy.serivce.ReaderService;
import com.lzxzjy.serivce.impl.ReaderServiceImpl;
import com.lzxzjy.util.CheckCodeUtil;
import com.lzxzjy.util.EncryptionUtil;
import com.lzxzjy.util.MailCodeUtil;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/registered/*")
public class RegisteredServlet extends BaseServlet {
    private String sendMailCode(Reader reader) throws MessagingException, UnsupportedEncodingException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String nowDay = simpleDateFormat.format(new Date());
        Session milSession = MailCodeUtil.createSession();

        MimeMessage message = new MimeMessage(milSession);
        message.setSubject("您有一条来自学海书舫图书馆的新消息");
        message.setFrom(new InternetAddress("zhenxi.lu@foxmail.com", "学海书舫图书馆", "UTF-8"));
        String mailCode = CheckCodeUtil.generateVerifyCode(6);
        message.setText("<h3 style=\"font-size: 16px\">\n" +
                "\t亲爱的" + ("".equals(reader.getReaderName()) ? "用户" : reader.getReaderName()) + "：\n" +
                "</h3>\n" +
                "<p style=\"font-size: 14px;\">\n" +
                "\t&nbsp;&nbsp;&nbsp;&nbsp;您好！您正在进行邮箱验证，本次请求的验证码为：" + mailCode + "，本验证码 15\n 分钟内有效，请在 15 分钟内完成验证。（请勿泄露此验证码）如非本人操作，请忽略该邮件。（这是一封自动发送的邮件，请不要直接回复）\n" +
                "</p>\n" +
                "<p style=\"text-align: right;\">学海书舫图书馆</p>\n" +
                "<p style=\"text-align: right;\">"+ nowDay +"</p>", "utf-8", "html");
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(reader.getReaderEmail()));
        Transport.send(message);
        return mailCode;
    }

    public void getMailCode(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, MessagingException {
        BufferedReader readerReader = request.getReader();
        String readerLine = readerReader.readLine();
        Reader reader = JSON.parseObject(readerLine, Reader.class);
        HttpSession session = request.getSession();
        String mailCode = sendMailCode(reader);
        session.setAttribute("mailCode", mailCode);
    }

    public void registeredReader(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, MessagingException {
        BufferedReader readerReader = request.getReader();
        String read = readerReader.readLine();
        JSONObject jsonObject = JSON.parseObject(read);
        String captcha = (String) jsonObject.get("captcha");
        HttpSession session = request.getSession();
        String mailCode = (String) session.getAttribute("mailCode");
        if (mailCode.equalsIgnoreCase(captcha)) {
            Reader reader = JSON.parseObject(JSON.toJSONString(jsonObject.get("reader")), Reader.class);
            ReaderService readerService = new ReaderServiceImpl();
            reader.setReaderPassword(EncryptionUtil.encrypt(reader.getReaderPassword()));
            reader.setReaderState(1);
            try {
                readerService.insertReader(reader);
            } catch (Exception e) {
                if(e.getMessage().contains("Duplicate entry '") && e.getMessage().contains("' for key 'tb_reader.uk_reader_email'")) {
                    response.getWriter().write("email");
                }
            }

        } else {
            response.getWriter().write("none");
        }
    }
}
